import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import Layout from "../layout/index.vue";
import { useAppStore } from "../store/app";
import NotFound from "../pages/common/404.vue";
import NoPermission from "../pages/common/403.vue";
import { useUserStore } from "../store/user";
import { usePermissionStore } from "../store/permisson";
import newsManageRoutes from "./newsManage";
import aboutUsManageRoutes from "./aboutUsManage";
import researchManageRoutes from "./researchManage";
import joinUsManageRoutes from "./joinUsManage";
import academicManageRoutes from "./academicManage";
import accessibilityManageRoutes from "./accessibilityManage";
import systemManageRoutes from "./systemManage";
import { PERMISSION_KEY } from "@/constants/common";

export const constantRoutes: RouteRecordRaw[] = [
    {
        path: "/login",
        component: () => import("../pages/login/index.vue"),
        meta: {
            hidden: true, // 在侧边栏隐藏
        },
    },

    {
        path: "/download",
        name: "download",
        component: () => import("../pages/download/index.vue"),
        meta: {},
    },
    {
        path: "/403",
        name: "NoPermission",
        component: NoPermission,
        meta: {
            hidden: true,
        },
    },
    {
        path: "/:pathMatch(.*)*",
        name: "NotFound",
        component: NotFound,
        meta: {
            hidden: true,
        },
    },
];

export const asyncRoutes: RouteRecordRaw[] = [
    {
        path: "/banner",
        component: Layout,
        redirect: "/banner/index",
        meta: { title: "banner管理", icon: "AI", onlyOneChild: true, permissionKey: 1 },
        children: [
            {
                path: "index",
                component: () => import("../pages/banner/index.vue"),
                name: "ai",
                meta: {
                    title: "banner管理",
                    permissionKey: PERMISSION_KEY[0].key, //1-banner管理 2-新闻动态 3-关于我们 4-研究方向 5-加入我们 6-学术交流 7-辅助功能 8-系统管理  9-人员管理 10-角色管理
                },
            },
        ],
    },
    ...newsManageRoutes,
    ...aboutUsManageRoutes,
    ...researchManageRoutes,
    ...joinUsManageRoutes,
    ...academicManageRoutes,
    ...accessibilityManageRoutes,
    ...systemManageRoutes,
];

const router = createRouter({
    history: createWebHistory(),
    routes: [...constantRoutes, ...asyncRoutes],
});

router.beforeEach((to) => {
    // 设置当前用户的最近使用菜单
    // const { adjustRecentUsedMenus } = useUserStore();
    // const { accessedRoutes } = usePermissionStore();
    // if (to.name !== "NotFound") {
    //     adjustRecentUsedMenus(to);
    // }
});

router.afterEach((to, from) => {
    const { appState } = useAppStore();
    appState.upperMenu = from.path;
    appState.upperTitle = from.meta.title as string;
});

export default router;
